import axios from 'axios'
import { baseURL } from '@/config'
import history from './history'
import Toast from '@/utils/Toast'
import { INIT_LANG, SERVER_LANG } from '@/config'

const instance = axios.create({
  baseURL,
  timeout: 6000
})

// add request interceptors
instance.interceptors.request.use(config => {
  const token = window.storage.get('token') || ''
  config.headers['Authorization'] = token
  window.progress.start()
  // before request config
  return config
}, (error) => {
  window.progress.done()
  return Promise.reject(error)
})

// add response interceptors
instance.interceptors.response.use(res => {
  const { status, data } = res
  window.progress.done()
  if (status === 200) {
    if (data.code === 200) {
      return Promise.resolve(data)
    } else {
      // before response config
      // 401 ----- 登录过期----------------------
      if (data.code === 401) {
        history.push('/login')
        window.storage.remove('token')
      }
    }
  }
  const lang = window.storage.get('lang') || INIT_LANG
  Toast.error(data[SERVER_LANG[lang]])
  return Promise.reject(res)
}, (error) => {
  window.progress.done()
  Toast.error(error?.message || '')
  return Promise.reject(error)
})

export const get = (url, params) => instance.get(url, params)
export const post = (url, data) => instance.post(url, data)